﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;

namespace Identity_MVC.Data
{
    public static class WebHostMigrationExtension
    {
        public static IHost MigrateDbContext<TContext>
            (this IHost host, Action<TContext, IServiceProvider> seeder) where TContext : DbContext
        {

            using (var scope=host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                var logger = services.GetRequiredService<ILogger<TContext>>();
                var context = services.GetRequiredService<TContext>();

                try
                {
                    context.Database.Migrate();

                    seeder(context, services);

                    logger.LogInformation($"执行DBContext {typeof(TContext).Name} seed方法成功!");
                }
                catch (Exception ex)
                {
                    logger.LogError(ex,$"执行DBContext {typeof(TContext).Name} seed方法失败!");
                }

            }

            return host;
        }
    }
}
